use async_std::fs;
use async_std::io::{Read, ReadExt, Write, WriteExt};
use async_std::task;
use std::time::Duration;

/// 处理单个连接：只要实现了 `Read + Write + Unpin + Send` 的异步流即可。
pub async fn handle_connection<S>(mut stream: S)
where
    S: Read + Write + Unpin + Send,
{
    let mut buffer = [0u8; 1024];

    if stream.read(&mut buffer).await.is_err() {
        return;
    }

    let get = b"GET / HTTP/1.1\r\n";
    let sleep = b"GET /sleep HTTP/1.1\r\n";

    let (status_line, filename) = if buffer.starts_with(get) {
        ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
    } else if buffer.starts_with(sleep) {
        task::sleep(Duration::from_secs(5)).await;
        ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
    } else {
        ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
    };

    let contents = match fs::read_to_string(filename).await {
        Ok(c) => c,
        Err(err) => {
            eprintln!("failed to read {filename}: {err}");
            return;
        }
    };

    let response = format!("{status_line}{contents}");

    if stream.write_all(response.as_bytes()).await.is_err() {
        return;
    }

    let _ = stream.flush().await;
}